package cn.iocoder.yudao.module.personal.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: huqngqi
 * @date: 2024/12/2 17:33
 * @description: 天气预警
 */
@Component
@Slf4j
public class WeatherWarningJob implements JobHandler {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SmsSendApi smsSendApi;

    @Override
    public String execute(String param) {
        if (StringUtils.isBlank(param)) {
            return "入参为空";
        }
        JSONArray paramJsonArray = JSONArray.parseArray(param);
        for(int i = 0; i < paramJsonArray.size(); i++){
            JSONObject jsonObject = paramJsonArray.getJSONObject(i);
            String mobiles = jsonObject.getString("mobile");
            if (StringUtils.isBlank(mobiles)) {
                continue;
            }
            Long channelId = jsonObject.getLong("channelId");
            String templateCode = jsonObject.getString("templateCode");
            Map<String, Object> templateParams = jsonObject.getJSONObject("templateParams");
            if(templateParams == null){
                templateParams = new HashMap<>();
            }
            String location = jsonObject.getString("location");
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("location", location);
            paramMap.put("key", "00876934f1a54a0b9a97e05007f30555");
            String result = HttpUtil.get("https://api.qweather.com/v7/warning/now", paramMap);
            log.info("result:{}", result);
            if (StringUtils.isBlank(result)) {
                return "天气预警提醒服务异常";
            }
            JSONObject jsonResult = JSONObject.parseObject(result);
            if (!"200".equals(jsonResult.get("code"))) {
                return "天气预警提醒服务异常";
            }
            //今天(${todayStr}): 气温${qwToday},请留意
            JSONArray warningJsonArray = jsonResult.getJSONArray("warning");
            for (int j = 0; j < warningJsonArray.size(); j++) {
                JSONObject dailyJsonObject = warningJsonArray.getJSONObject(j);
                String id = dailyJsonObject.getString("id");
                String sender = dailyJsonObject.getString("sender");
                String pubTime = dailyJsonObject.getString("pubTime");
                String title = dailyJsonObject.getString("title");
                String text = dailyJsonObject.getString("text");
                if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("weather_warning_" + id))){
                    continue;
                }
                stringRedisTemplate.opsForValue().set("weather_warning_"+id, id, 7, TimeUnit.DAYS);
                StringBuilder nowStr = new StringBuilder();
                nowStr.append(title).append(" ");
                log.info("天气预警:{}", nowStr);
                templateParams.put("qwToday", nowStr);
                templateParams.put("todayStr", DateUtil.formatDate(new Date()));
                String[] mobilesAttr = mobiles.split(",");
                for (String mobile : mobilesAttr) {
                    SmsSendSingleToUserReqDTO reqDTO = new SmsSendSingleToUserReqDTO();
                    reqDTO.setMobile(mobile);
                    reqDTO.setTemplateCode(templateCode);
                    reqDTO.setTemplateParams(templateParams);
                    reqDTO.setChannelId(channelId);
                    smsSendApi.sendSingleSmsDirectToMobile(reqDTO);
                }
            }
        }
        return "执行成功";
    }
}
